<script setup>
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { ElMessage, ElMessageBox, genFileId } from "element-plus";
import { getOne, modifyById } from "@/api/association/association";
import { downLoadFile } from "@/api/common/common";

import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

components: { Editor, Toolbar }
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
  }, 1500)
})

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}


// const handleUpload = async () => {
//   const res = await uploadForm(uploadRef.value);
//   form.value.applicationForm = res.data;
//   ElMessage.success(res.msg || "文件上传成功");
// };

// 处理文件回显 8415bc1f-a4da-473b-9010-425aa81cb8e9_R-C.jpg
const handleGetOne = async () => {
  const res = await getOne();

  //获取到文件路径
  let path = res.data.applicationForm
    if (path){
      let fileName = path.split("_").slice(1).join("_")

      res.data.applicationFormArr = [{
        name:fileName,
        response:{
          data:path
        }
      }]
    }

  form.value = res.data;
};
const handleModifyById = async () => {
  let formData = JSON.parse(JSON.stringify(form.value));
  formData.applicationForm = form.value.applicationFormArr[0].response.data
  const res = await modifyById(form.value.id, formData);
  ElMessage.success(res.msg || "修改成功");
};

onMounted(() => {
  handleGetOne();
});

const onSubmit = async () => {
  try {
    await ElMessageBox.confirm("确认提交此次变更吗？", "温馨提示", {
      confirmButtonText: "OKK",
      cancelButtonText: "手滑了一下下",
      type: "warning",
    });
    handleModifyById();
  } catch (error) {
    return;
  }
  //   ElMessageBox.confirm(
  //     '确认提交此次变更吗?',
  //     '温馨提示',
  //     {
  //       confirmButtonText: 'O的K',
  //       cancelButtonText: '手滑了一下下',
  //       type: 'warning',
  //     }
  //   )
  //     .then(() => {
  //       ElMessage({
  //         type: 'success',
  //         message: 'Delete completed',
  //       })
  //     })
  //     .catch(() => {
  //       ElMessage({
  //         type: 'info',
  //         message: 'Delete canceled',
  //       })
  //     })
};

const form = ref({
  id: "",
  introduction: "",
  structure: "",
  statutes: "",
  contact: "",
  significance: "",
  applicationForm: "", // 入会申请表（用于提交）
  applicationFormArr: [], // 入会申请表数组（用于展示）
});

const upload = ref();

const handleExceed = (files) => {
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};

// 手动获取请求头
let headers = ref({
  token: localStorage.getItem("Token"),
});

//文件上传成功的回调
function handleUploadSuccess(file){
  // console.log(file)
  // console.log(form.value.applicationFormArr[0].response.data)
}

//下载相关
function onPreview(file){
  console.log("file",file)
  downLoadFile(file.response.data)
}

</script>

<template>
  <el-card style="max-width: 680px; margin: 0 auto">
    <template #header>
      <div class="card-header card-title">
        <span>协会信息</span>
      </div>
    </template>

    <el-form :model="form" label-width="auto" style="max-width: 600px">
      <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>

      <el-form-item label="协会介绍">
        <el-input v-model="form.introduction" type="textarea" />
      </el-form-item>
      <el-form-item label="组织架构">
        <el-input v-model="form.structure" type="textarea" />
      </el-form-item>
      <el-form-item label="协会章程">
        <el-input v-model="form.statutes" type="textarea" />
      </el-form-item>
      <el-form-item label="联系协会">
        <el-input v-model="form.contact" type="textarea" />
      </el-form-item>
      <el-form-item label="加入协会的意义">
        <el-input v-model="form.significance" type="textarea" />
      </el-form-item>
      <el-form-item label="入会申请表">
        <el-upload
          v-model:file-list="form.applicationFormArr"
          ref="upload"
          class="upload-demo"
          :limit="1"
          action="/api/common/upload"
          :headers="headers"
          :on-success="handleUploadSuccess"
          :on-preview="onPreview"
          :on-exceed="handleExceed"
        >
          <template #trigger>
            <el-button>
              <el-icon style="vertical-align: middle; margin-right: 5px">
                <Upload />
              </el-icon>
              点击上传
            </el-button>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary OkBtn" @click="onSubmit">O的K</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>
.card-title {
  text-align: center;
}

.OkBtn {
  margin-left: 50%;
}
</style>
